package com.pandora.common.util;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;
import org.mindrot.jbcrypt.BCrypt;

import java.io.IOException;

/**
 * @author developer
 */
public class VerifyUtil {

    public static boolean isEmpty(String s) {
        if (s == null || "".equals(s) || s.length() == 0) {
            return true;
        }
        return false;
    }

    public static boolean smsSend(String mobile, String content) {
        String txt = StringUtils.getStrParam("%s %s", Constants.SMS_SIGN, content);
        HttpClient httpClient = new HttpClient();
        httpClient.getHostConfiguration().setHost(Constants.SMS_HOST, 80, "http");
        PostMethod postMethod = new PostMethod(Constants.SMS_METHOD);
        postMethod.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8");
        NameValuePair un = new NameValuePair("un", Constants.SMS_USER);
        NameValuePair pw = new NameValuePair("pw", Constants.SMS_PASSWORD);
        NameValuePair phone = new NameValuePair("phone", mobile);
        NameValuePair msg = new NameValuePair("msg", txt);
        NameValuePair rd = new NameValuePair("rd", "1");
        postMethod.setRequestBody(new NameValuePair[] { un, pw, phone, msg, rd });
        try {
            int statusCode = httpClient.executeMethod(postMethod);
            String res = new String(postMethod.getResponseBodyAsString().getBytes("UTF-8"));
            if (statusCode != MagicConst.NUM_200) {
                return false;
            }
            return "0".equals(res.split("\n")[0].split(",")[1]);
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
    }

    public static String bCryptEnc(String s) {
        return BCrypt.hashpw(s, BCrypt.gensalt());
    }

    public static boolean bCryptCheck(String s, String hash) {
        boolean b = false;
        try {
            b = BCrypt.checkpw(s, hash);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return b;
    }

}
